/*
 Notes on using the UART for a MSP430x2xx.  Copyright Matt Stump 2009.
 
 This example specifically uses the MSPF249 on the OLIMEX MSP430-P249

*/

#include <io430.h>
#include <intrinsics.h>
#include <stdint.h>

const char string1[] = { "Hello World\r\n" };
unsigned int i;

void
main()
{
	// Stop watchdog timer to prevent time out reset
	WDTCTL				=	WDTPW + WDTHOLD;
	
	// Set SCLK to calibrated 1 MHz DCO
	BCSCTL1				=	CALBC1_1MHZ;
	DCOCTL				=	CALDCO_1MHZ; 
	
	// setup ACLK source and parameters, external crystal is 32.768 kHz
	BCSCTL3				=	LFXT1S_0 | XT2S_0 |  XCAP_1;
	
	// UART
	UCA0CTL1			=	UCSSEL_1 | UCSWRST;	// use ACLK as uart clock source, hold the UART
	UCA0CTL0			=	0;					// UART ASYNC MODE, 8N1, LSB
	
	// configure the ports
	P1DIR				=	0xFF;				// All P1.x outputs
	P1OUT				=	0;					// All P1.x reset
	P2DIR				=	0xFF;				// All P2.x outputs
	P2OUT				=	0;					// All P2.x reset
	P3SEL				=	0x30;				// P3.4,5 = USCI_A0 TXD/RXD
	P3DIR				=	0xFF;				// All P3.x outputs
	P3OUT				=	0;					// All P3.x reset
	P4DIR				=	0xFF;				// All P4.x outputs
	P4OUT				=	0;					// All P4.x reset
	
	// set the baud to 4800, see device family guide
	UCA0BR0				=	0x06;				
	UCA0BR1				=	0x00;
	
	// the modulation needs to be set to the value in the table of the
	// device family guide.  For this device using a watch crystal to obtain
	// a baud of 4800 the guide says I need a UCBRSx value of 7.  So how does
	// UCBRS2 + UCBRS1 + UCBRS0 == 7?  The answer is that UCBRS0 == 2 UCBRS1 == 4
	// and UCBRS2 == 8 for this device.  Add them all togeather and you get 14.
	// The bit pattern for 0b00001110 and the bit pattern for 7 is 0b00000111.
	// If you ignore the first bit of 14 like it is ignored in the modulation register
	// then 14 magicly becomes 7.  So in conclusion, add up the numbers
	// that equal the value in the table if you were to ignore the first bit.
	// Real intuitive huh?  Great job on the docs for that one TI!
	UCA0MCTL			=	UCBRS2 + UCBRS1 + UCBRS0;
	
	// 9600
	//UCA0BR0				= 0x03;					// 32kHz/9600 = 3.41
	//UCA0BR1				= 0x00;
	//UCA0MCTL			= UCBRS1 + UCBRS0;
	
	UCA0CTL1			&=	~UCSWRST;			// release the UART
	IE2_bit.UCA0TXIE	=	1;					// enable TX interrupt
	
	for (;;)
		__low_power_mode_3();
}

#pragma vector = USCIAB0TX_VECTOR
__interrupt void USCIAB0TX_ISR (void)
{
  UCA0TXBUF = string1[i++];                 // TX next character

  if (i == sizeof string1 - 1)              // TX over?
    IE2 &= ~UCA0TXIE;                       // Disable USCI_A0 TX interrupt
}

